// lib/pages/search_page.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class SearchPage extends StatefulWidget {
  const SearchPage({super.key});

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  final TextEditingController _controller = TextEditingController();
  final List<String> _history = []; // 简易内存历史，可换成 GetStorage 持久化
  final List<String> _hots = ['iPhone 16', '耳机', '键盘', '牛奶', '显示器'];

  void _doSearch([String? preset]) {
    final q = (preset ?? _controller.text).trim();
    if (q.isEmpty) return;

    // 简单维护历史
    setState(() {
      _history.remove(q);
      _history.insert(0, q);
      if (_history.length > 8) _history.removeLast();
    });

    Get.toNamed('/search_result', arguments: {'q': q});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        titleSpacing: 0,
        title: Container(
          margin: const EdgeInsets.only(right: 8),
          padding: const EdgeInsets.symmetric(horizontal: 8),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Row(
            children: [
              Expanded(
                child: TextField(
                  enabled: true,
                  controller: _controller,
                  autofocus: true,
                  textInputAction: TextInputAction.search,
                  onSubmitted: (_) => _doSearch(),
                  decoration: InputDecoration(
                    hintText: '输入搜索内容',
                    isCollapsed: true,
                    contentPadding: const EdgeInsets.symmetric(
                        vertical: 12, horizontal: 12),
                    prefixIcon: const Icon(Icons.search),
                    border: InputBorder.none,
                    filled: true,
                    fillColor:
                        Colors.grey.withValues(alpha: 0.1), // 避免 withOpacity 警告
                  ),
                ),
              ),
              if (_controller.text.isNotEmpty)
                IconButton(
                  icon: const Icon(Icons.close, size: 18),
                  onPressed: () {
                    _controller.clear();
                    setState(() {});
                  },
                ),
            ],
          ),
        ),
        actions: [
          TextButton(onPressed: _doSearch, child: const Text('搜索')),
        ],
      ),
      body: ListView(
        padding: const EdgeInsets.all(12),
        children: [
          if (_history.isNotEmpty) ...[
            _SectionTitle(
              title: '最近搜索',
              trailing: IconButton(
                icon: const Icon(Icons.delete_outline, size: 18),
                onPressed: () => setState(() => _history.clear()),
              ),
            ),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: _history
                  .map((e) => _ChipButton(text: e, onTap: () => _doSearch(e)))
                  .toList(),
            ),
            const SizedBox(height: 16),
          ],
          _SectionTitle(title: '热门搜索'),
          SizedBox(height: 16),
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: _hots
                .map((e) => _ChipButton(text: e, onTap: () => _doSearch(e)))
                .toList(),
          ),
        ],
      ),
    );
  }
}

class _SectionTitle extends StatelessWidget {
  final String title;
  final Widget? trailing;
  const _SectionTitle({required this.title, this.trailing});

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Text(title, style: const TextStyle(fontWeight: FontWeight.w600)),
        const Spacer(),
        if (trailing != null) trailing!,
      ],
    );
  }
}

class _ChipButton extends StatelessWidget {
  final String text;
  final VoidCallback onTap;
  const _ChipButton({required this.text, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return InkWell(
      borderRadius: BorderRadius.circular(16),
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        decoration: BoxDecoration(
          color: Colors.grey.withValues(alpha: 0.12),
          borderRadius: BorderRadius.circular(16),
        ),
        child: Text(text),
      ),
    );
  }
}
